package handle

import (
	"chat3/api/request"
	"chat3/consts"
	"chat3/internal/dao"
	"chat3/internal/model"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golangblogs/gojwt"
	"net/http"
	"time"
)

func Register(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile: req.Mobile,
	}, &user)
	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户已存在",
			"data": nil,
		})
		return
	}
	m := model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}
	if !dao.Create(&m) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户注册成功",
		"data": nil,
	})
}

func Logon(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "参数验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "账号或密码错误",
			"data": nil,
		})
		return
	}
	token, err := jwt2.NewJWT(consts.JWT_KEY).CreateToken(jwt2.CustomClaims{ID: uint(user.Id),
		StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().Unix() + 3600*24*2},
	})
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
}
